package com.budwk.app.sqfwV2.service.childrenVisitation;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.dto.PersonnelTagDTO;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.PersonInfo;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.PersonInfoService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BasePdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService.CompleteFlowCommonPdfService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.result.GeneratorPdfWordResult;
import com.budwk.app.sqfwV2.component.ChildrenVisitationComponent;
import com.budwk.app.sqfwV2.dto.dto.PersonInfoDTO;
import com.budwk.app.sqfwV2.dto.dto.childrenVisits.ChildrenVisitationPdfDTO;
import com.budwk.app.sqfwV2.enums.FileServiceConfigEnum;
import com.budwk.app.sqfwV2.generator.childrenVisitation.pdf.ChildrenVisitsWord;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.IocBean;

import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 儿童探访记录
 * @since 2024-04-23
 *
 * 白云区儿童探访记录 ChildrenVisitation
 */
@IocBean
@Slf4j
public class ChildrenVisitationPdfService extends CompleteFlowCommonPdfService{

    @Override
    public void createPdfAndMsg(CompleteFlowPdfParamForController paramForController) {
        super.createPdfAndMsg(paramForController);
    }

    @Override
    public void reCreatePdfAndMsg(CompleteFlowPdfParamForController paramForController) {
        super.reCreatePdfAndMsg(paramForController);
    }

    @Override
    public GeneratorPdfWordResult createPdfSync(CompleteFlowPdfParamForController paramForController) {
        return super.createPdfSync(paramForController);
    }

    /**
     * 获取用户自定义字段 代码生成器已经自动填充
     * 无需特殊修改
     *
     * @param paramData json字符串
     * @return 结果
     */
    @Override
    protected AbstractCustomerPdfCreateField getCustomerPdfField(String paramData) {
        return JSONObject.parseObject(paramData, ChildrenVisitationPdfDTO.class);
    }

    @Override
    protected void beforeInsertForSummary(Sqfw_formSummary_new formSummary) {
        ChildrenVisitationPdfDTO pdfDTO = JSONObject.parseObject(formSummary.getParamData(), ChildrenVisitationPdfDTO.class);
        if (pdfDTO.getFillDate() != null) {
            formSummary.setFillDate(Date.from(pdfDTO.getFillDate().atZone(ZoneId.systemDefault()).toInstant()));
        }
        // 组装人员信息
        buildPerson(pdfDTO, formSummary);
        ChildrenVisitationPdfDTO f = StrUtil.serializerData(ChildrenVisitationPdfDTO.class, pdfDTO);
        String paramData = JSONObject.toJSONString(f);
        formSummary.setParamData(paramData);
        log.info("children beforeInsertForSummary param end1: {}", paramData);
    }

    private void buildPerson(ChildrenVisitationPdfDTO pdfDTO, Sqfw_formSummary_new formSummary) {
        if (StringUtils.isEmpty(pdfDTO.getPersonId())) {
            // 插入用户信息
            String personId = insertChildren(formSummary);
            pdfDTO.setPersonId(personId);
            return;
        }
        PersonInfoService personInfoService = NutzIocUtils.getBean(PersonInfoService.class);
        PersonInfo p = personInfoService.fetch(pdfDTO.getPersonId());
        if (p == null) {
            throw new AppException("提交人员信息不存在！");
        }
        List<PersonnelTagDTO> specialMark = p.getSpecialMark();
        Optional<PersonnelTagDTO> first = specialMark.stream().filter(e -> e.getBusinessType().equals(SupportBusinessTypeEnum.CHILDREN_VISITATION.getName())).findFirst();
        if (first.isEmpty()) {
            throw new AppException("儿童类别参数未查询到！");
        }
        PersonnelTagDTO.Dict dict = first.get().getTag().get(0);
        if (ChildrenVisitationComponent.CHILDREN_TYPE.equals(dict.getBusinessType())) {
            pdfDTO.setChildrenType(dict.getKey());
        }
        pdfDTO.setAddress(p.getAddress()).setHouseholdAddress(p.getRegAddress());
        pdfDTO.setIsLiveRegisteredAddress(p.getAddress().equals(p.getRegAddress()) ? CommonConstants.TRUE : CommonConstants.FALSE);
        pdfDTO.setIdcard(p.getIdNumber()).setCitizenSex(p.getGender()).setBirthday(p.getBirthDate());
    }

    public String insertChildren(Sqfw_formSummary_new formSummary) {
        PersonInfoDTO reqVo = new PersonInfoDTO();
        ChildrenVisitationPdfDTO f = JSONObject.parseObject(formSummary.getParamData(), ChildrenVisitationPdfDTO.class);
        // 按照五级+身份证号检查用户是否存在
        PersonInfoService personInfoService = NutzIocUtils.getBean(PersonInfoService.class);
        PersonInfo personInfo = personInfoService.getPersonInfo(f.getIdcard());
        if (personInfo != null) {
            reqVo.setId(personInfo.getId());
        }
        // 后期等待修改..........
        reqVo.setName(f.getVisitedName())
                .setProvince(formSummary.getProvince())
                .setCity(formSummary.getCity())
                .setDistrict(formSummary.getDistrict())
                .setCounty(formSummary.getCounty())
                .setCommunity(formSummary.getCommunity())
                .setCreateBy(formSummary.getCreateBy())
                .setCreateDate(formSummary.getCreateDate() != null ? formSummary.getCreateDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null)
                .setUpdateBy(formSummary.getUpdateBy())
                .setCreateDate(formSummary.getUpdateDate() != null ? formSummary.getUpdateDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null)
                .setIdNumber(f.getIdcard())
                .setAddress(f.getAddress())
                .setRegAddress(f.getHouseholdAddress())
        ;
        reqVo.setChildrenType(f.getChildrenType())
                .setOtherCategory(f.getOtherCategory())
                .setBusinessType(SupportBusinessTypeEnum.CHILDREN_VISITATION.getName());
        PersonInfo p = personInfoService.saveOrUpdatePerson(reqVo);
        return p.getId();
    }

    /**
    * 允许用户自定义填充在创建pdf时所提供的数据
    *
    * @param pdfGenerateParam 创建pdf所提供的数据
    */
    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam) {

    }

    /**
     * 在这里设置生成pdf的所有generator
     *
     * @param pdfGenerateParam 创建pdf的参数
     * @return 生成pdf的generator合集
     */
    @Override
    protected List<BasePdfGenerator> getPdfGenerator(PdfGenerateParam pdfGenerateParam) {
        List<BasePdfGenerator> generatorList = Lists.newArrayList();
        // 在这里添加自己的generator
        generatorList.add(new ChildrenVisitsWord());
        return generatorList;
    }

    /**
    * 用户自定义下载pdf文件的名称
    *
    * @param pdfGenerateParam 创建pdf所提供的参数
    * @return 结果
    */
    @Override
    protected String getDownloadFileName(PdfGenerateParam pdfGenerateParam) {
        return FileServiceConfigEnum.CA.getFileName();
    }

    /**
    * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
    *
    * @return 返回数据
    */
    @Override
    public String getSummaryType() {
        return SupportBusinessTypeEnum.CHILDREN_VISITATION.getName();
    }

    @Override
    protected void beforeReGenPdf(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummaryNews, Map<String, Object> businessDataMap) {
        String paramData = formSummaryNews.getParamData();
        beforeInsertForSummary(formSummaryNews);
        String paramData1 = formSummaryNews.getParamData();
        if (!paramData.equals(paramData1)) {
            // 修改数据
            SqfwFormsummaryNewService sqfwFormsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
            sqfwFormsummaryNewService.updateIgnoreNull(formSummaryNews);
        }
    }
}
